<script setup>
import {onMounted, ref} from 'vue';
import luckysheet from "luckysheet";
import index from "@/components/analysisSheetComponents/soil/tmpl96/index.vue";
import {useAnalysetStore} from "@/store/index";
import AnalyesAPI from "@/api/system/analyes";
import {filterValidSampleAdatas, filterValidSamples, removeNullSampleSN} from "@/utils/method";
import Index from "@/components/analysisSheetComponents/component/index.vue";
import CommonAPI from "@/api/common/index";

let options = {
  container: "luckysheet", //luckysheet为容器id
  lang: 'zh',
  autoCalculate: true,
  data: [
    {
      "column": 10, // 列数
      "defaultRowHeight": 30, // 自定义行高
      "defaultColWidth": 100, // 自定义列宽
      "celldata": [
        // 初始化表格数据，第一行包含表头
        {"r": 0, "c": 0, "v": "元素（模式）",}, // A1
        //第二行
        {"r": 1, "c": 0, "v": "检出限(µg/L)",}, // A1
        //第三行
        {"r": 2, "c": 0, "v": "样品编号",}, // A1
        {"r": 2, "c": 1, "v": "类型",}, // A1
        {"r": 2, "c": 2, "v": "取样量m(g)",}, // A1
        {"r": 2, "c": 3, "v": "干物质含量Wdm(%)",}, // A1
        {"r": 2, "c": 4, "v": "稀释倍数f",}, // A1
        {"r": 2, "c": 5, "v": "机读浓度ρ()",},
        {"r": 2, "c": 6, "v": "含量ω()",},
        {"r": 2, "c": 7, "v": "测定结果",},
        {"r": 2, "c": 8, "v": "机读浓度ρ() ",},
        {"r": 2, "c": 9, "v": "含量ω() ",},
        {"r": 2, "c": 10, "v": "测定结果 ",},
        {"r": 2, "c": 11, "v": " 机读浓度ρ() ",},
        {"r": 2, "c": 12, "v": " 含量ω() ",},
        {"r": 2, "c": 13, "v": " 测定结果 ",},
        {"r": 2, "c": 14, "v": " 机读浓度ρ( ) ",},
        {"r": 2, "c": 15, "v": " 含量ω( ) ",},
        {"r": 2, "c": 16, "v": " 测定结果  ",},
        {"r": 0, "c": 17, "v": "备注",},
      ], // 初始化数据
      "config": {
        "merge": {
          "0_0": {
            "r": 0, // 起始行
            "c": 0, // 起始列
            "rs": 1, // 跨越的行数
            "cs": 5  // 跨越的列数
          },
          "1_0": {
            "r": 1, // 起始行
            "c": 0, // 起始列
            "rs": 1, // 跨越的行数
            "cs": 5  // 跨越的列数
          },
          "0_5": {
            "r": 1, // 起始行
            "c": 0, // 起始列
            "rs": 1, // 跨越的行数
            "cs": 3  // 跨越的列数
          },
          "1_5": {
            "r": 1, // 起始行
            "c": 0, // 起始列
            "rs": 1, // 跨越的行数
            "cs": 3  // 跨越的列数
          },
          "0_8": {
            "r": 1, // 起始行
            "c": 0, // 起始列
            "rs": 1, // 跨越的行数
            "cs": 3  // 跨越的列数
          },
          "1_8": {
            "r": 1, // 起始行
            "c": 0, // 起始列
            "rs": 1, // 跨越的行数
            "cs": 3  // 跨越的列数
          },
          "0_11": {
            "r": 1, // 起始行
            "c": 0, // 起始列
            "rs": 1, // 跨越的行数
            "cs": 3  // 跨越的列数
          },
          "1_11": {
            "r": 1, // 起始行
            "c": 0, // 起始列
            "rs": 1, // 跨越的行数
            "cs": 3  // 跨越的列数
          },
          "0_14": {
            "r": 1, // 起始行
            "c": 0, // 起始列
            "rs": 1, // 跨越的行数
            "cs": 3  // 跨越的列数
          },
          "1_14": {
            "r": 1, // 起始行
            "c": 0, // 起始列
            "rs": 1, // 跨越的行数
            "cs": 3  // 跨越的列数
          },

          "0_17": {
            "r": 1, // 起始行
            "c": 0, // 起始列
            "rs": 3, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
        }, // 合并单元格
        "rowlen": {}, // 表格行高
        "columnlen": { // 设置列宽
          "0": 100,
          "1": 100,
          "2": 100,
          "3": 130,
          "4": 130,
          "5": 130,
          "6": 130,
          "7": 130,
          "8": 130,
          "9": 130,
        }, // 表格列宽
      },
    }
  ],
  showinfobar: false, // 隐藏信息栏
  showtoolbar: true, // 隐藏工具栏
};
const tableOption = ref([
  {table: '仪器名称', id: 1,}
])
const switchAB = ref(true)
const sheetData = ref('')
const jsonData = ref(null)
const waterForm = ref({
  bdatas: {
    dcwName: [],
    jcx: [],
    rypz: Array.from({length: 4}, () => ({
      bzzbyph: '',
      bzzbynd: '',
      zbyyxrq: '',
      bzsyynd: '',
      pzrq: '',
    })),
    bzqx: {},
    ys: {},
    jhd: {},
    pxycd_fx: {},
    jbycd_fx: {},
    zky_fx: {},
  },
  pxycd: [],
  jbycd: [],
  unit: {},
  device: {
    device_name: [],
    device_model: [],
    device_number: [],
  },
})
const listB = ref({
  kbyList: [],
  qxyList: [],
  pxyList: [],
  bzyList: [],
})
const checkTime = ref('')
const processedData = ref([])
const cdatas = ref([])
const checkDialogVisible = ref(false)
const analyseStatusPage = useAnalysetStore()
const record_sn = analyseStatusPage.waterForm.record_sn
const switchAdd = ref(true)

let assignedDialogVisible = ref(false)
const selectedUsers = ref([])
const addSampleForm = ref({
  device_name: [],
})

// 在组件挂载后初始化 Lucky-sheet
onMounted(() => {
  // 初始化表格
  luckysheet.create(options);
  // 获取表单信息
  getWaterCapacity()
  getMethod()
  getDevicList()
});


// 获取仪器接口
const getDevicList = () => {
  CommonAPI.getdevice().then(res => {
    selectedUsers.value = res
  })
}

const fetchSearchResults = (query) => {
  if (query === '') return
  CommonAPI.getdevice({device_name: query}).then(data => {
    selectedUsers.value = data
  })
}

// 获取信息(也要粘贴)
const getMethod = () => {
  waterForm.value.task_name = analyseStatusPage.waterForm.task_number //任务名称
  waterForm.value.method = analyseStatusPage.waterForm.tableItem.test_method
      ? analyseStatusPage.waterForm.tableItem.test_method
      : analyseStatusPage.waterForm.tableItem.test_method_number;//分析方法
  waterForm.value.category_id = analyseStatusPage.waterForm.tableItem.sample_category // 样品类别
}

// 获取——获取 水质容量A   工作表
const getWaterCapacity = () => {
  let josn = {
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    task_id: analyseStatusPage.waterForm.taskId,
    // id: 7,
    record_sn: record_sn,
    // record_sn: 49,
  }
  AnalyesAPI.getAnalyseACapacity(josn).then(data => {
    // console.log('获取水质容量 A单', data)
    if (!Array.isArray(data) || data.length !== 0) {
      waterForm.value = data
      waterForm.value.bdatas = Array.isArray(data.bdatas) && data.bdatas.length === 0 ? {} : data.bdatas;
      waterForm.value.unit = Array.isArray(data.unit) && data.unit.length === 0 ? {} : data.unit;
      sheetData.value = data.configs
      options.data = sheetData.value
      luckysheet.create(options);
      processedData.value = data.adatas
    } else {
      waterForm.value.device = {
        device_name: [],
        device_model: [],
        device_number: [],
      }
    }
  })
}


// 保存新增表单
const handleAddWaterPh = () => {
  console.log(luckysheet.getLuckysheetfile())
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  const data = options.data[0].data.map(row => {
    return row
        .map(cell => {
          return cell ? {
            field: cell.m || "默认字段",
            value: cell.v || null
          } : null;
        })
        .filter(cell => cell !== null); // 删除 null 值
  });
  console.log(data);
  processedData.value = filterValidSampleAdatas(processData(data));
  cdatas.value = filterValidSamples(processDate(data));
  console.log(cdatas.value)
  if (waterForm.value.check_status !== undefined) {
    delete waterForm.value.check_status
    delete waterForm.value.reviewer_id
  }

  //   调保存新增接口
  AnalyesAPI.addWaterCapacity({
    ...waterForm.value,
    record_sn: record_sn,
    task_id: analyseStatusPage.waterForm.taskId,
    configs: sheetData.value,
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    adatas: processedData.value,
    cdatas: cdatas.value,
  }).then(data => {
    console.log('调接口拿数据', data)
    ElMessage.success('保存成功！')
    switchAdd.value = false
  })
}

// 处理能用的数据
const processData = (data) => {
  if (!data || data.length < 3) return [];

  // 提取表头信息
  const header1 = data[0].map(item => item.value).filter(value => value !== null);
  const header2 = data[1].map(item => item.value).filter(value => value !== null);
  const header3 = data[2].map(item => item.value).filter(value => value !== null);

  waterForm.value.bdatas.dcwName.push(...header1.slice(1, 5));
  waterForm.value.bdatas.jcx.push(...header2.slice(1, 6));

  // 提取数据行
  const rows = data.slice(3).map(rowData => rowData.map(item => item.value));

  // 构建嵌套结构
  return rows.map(row => {
    const result = header3.slice(0, 17).reduce((acc, key, index) => {
      acc[key] = row[index];
      return acc;
    }, {});
    result[header1[5]] = row[17]; // 额外的字段
    return result;
  });
};

// 剔除样品浓度ω( )
const extractBracketContent = (text) => {
  const match = text.match(/\((.*?)\)/);
  return match ? match[1] : text; // 如果匹配成功，返回括号内的内容，否则返回原文本
};
const processDate = (data) => {
  if (!data || data.length < 3) {
    return [];
  }
  // 提取表头信息
  const header1 = data[0].map(item => item.value).filter(value => value !== null);
  const header2 = data[1].map(item => item.value).filter(value => value !== null);
  const header3 = data[2].map(item => item.value).filter(value => value !== null);
  // 提取数据行
  // const row = data[2].map(item => item.value);
  const row = data.slice(3).map(rowData => rowData.map(item => item.value));
  console.log(row)
  // 构建嵌套结构
  const resultArray = [];
  for (let i = 0; i < row.length; i++) {
    const currentRow = row[i];
    const result = {
      sample_sn: currentRow[0] || null,
      type: currentRow[1] || null,
      datas: [
        {
          name: header1[1] || null,
          cdjg: currentRow[7] || null,
          limit_val: header2[1] || null,
          dw: extractBracketContent(header3[6]) || null,
        },
        {
          name: header1[2] || null,
          cdjg: currentRow[10] || null,
          limit_val: header2[2] || null,
          dw: extractBracketContent(header3[9]) || null,
        },
        {
          name: header1[3] || null,
          cdjg: currentRow[13] || null,
          limit_val: header2[3] || null,
          dw: extractBracketContent(header3[12]) || null,
        },
        {
          name: header1[4] || null,
          cdjg: currentRow[16] || null,
          limit_val: header2[4] || null,
          dw: extractBracketContent(header3[15]) || null,
        },
      ],
    };
    resultArray.push(result);
  }
  return resultArray;
};


// 打开分析仪器
const handleOpen = () => {
  assignedDialogVisible.value = true
}

const handleClose = () => {
  assignedDialogVisible.value = false
}


// 添加表格
const handleSureSample = () => {
  const selectedDevices = selectedUsers.value.filter(device => addSampleForm.value.device_name.includes(device.id));
  waterForm.value.device.device_name = selectedDevices.map(device => device.device_name);
  waterForm.value.device.device_model = selectedDevices.map(device => device.device_model);
  waterForm.value.device.device_number = selectedDevices.map(device => device.device_number);
  assignedDialogVisible.value = false
}

const handleDelete = (index) => {
  waterForm.value.device.device_name.splice(index, 1);
  waterForm.value.device.device_model.splice(index, 1);
  waterForm.value.device.device_number.splice(index, 1);
}


const filterParallelSamples = (data) => {
  return data.filter(item => item.类型 === "平行样");
};

const filterJbSamples = (data) => {
  // 筛选出类型为 "平行样" 的数据
  return data.filter(item => item.类型 === "加标样");
};

const filterKbSamples = (data) => {
  return data.filter(item => item.类型 === "空白样");
};

const filterQxSamples = (data) => {
  // 筛选出类型为 "平行样" 的数据
  return data.filter(item => item.类型 === "校核点");
};

// 筛选出类型为 "质控样" 的数据，并提取括号中的内容
const filterAndExtract = (data) => {
  return data.filter(item => item.类型 === "质控样")
      .map(item => {
        // 使用正则表达式提取括号中的内容
        const match = item.样品编号.match(/\((.*?)\)/);
        const extractedValue = match ? match[1] : null; // 提取括号中的值
        return {
          ...item,
          extractedSampleNumber: extractedValue // 添加提取出来的值
        };
      });
};


const handleSwitch = () => {
  switchAB.value = !switchAB.value
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  const data = options.data[0].data.map(row => {
    return row
        .map(cell => {
          return cell ? {
            field: cell.m || "默认字段",
            value: cell.v || null
          } : null;
        })
        .filter(cell => cell !== null); // 删除 null 值
  });
  listB.value.kbyList = filterKbSamples(filterValidSampleAdatas(processData(data)));
  listB.value.qxyList = filterQxSamples(filterValidSampleAdatas(processData(data)));
  listB.value.pxyList = filterParallelSamples(filterValidSampleAdatas(processData(data)));
  listB.value.bzyList = filterAndExtract(filterValidSampleAdatas(processData(data)));
  listB.value.jbyList = filterJbSamples(filterValidSampleAdatas(processData(data)));
  console.log(listB.value)
}
</script>

<template>
  <div class="card">
    <div v-show="switchAB">
      <el-card class="box-card">
        <h1 style="text-align: center">土壤和沉积物 电感耦合等离子体质谱法分析原始记录（A面）</h1>
        <div>SXLPHJ/JL/CX-22-96</div>
        <table class="table">
          <tr>
            <td colspan="3" style="width: 25%;">任务编号</td>
            <td colspan="8">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.task_name"/>
            </td>
            <td colspan="4">采样日期</td>
            <td colspan="5">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.sampling_time"/>
            </td>
            <td colspan="4">分析日期</td>
            <td colspan="5">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.anal_time"/>
            </td>
          </tr>
          <tr>
            <td colspan="3">分析方法</td>
            <td colspan="8">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.method">
              </el-input>
            </td>
            <td colspan="4">环境温度</td>
            <td colspan="5">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.temperature">
                <template #append>
                  <span style="background-color: transparent;color: black">℃</span>
                </template>
              </el-input>
            </td>
            <td colspan="4">环境湿度</td>
            <td colspan="5">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.humidity">
                <template #append>
                  <span style="background-color: transparent;color: black">%RH</span>
                </template>
              </el-input>
            </td>
          </tr>
          <tr>
            <td colspan="3">分析仪器</td>
            <td colspan="1" @click="handleOpen" style="width: 100px;">
              <div v-for="(item,index) in  waterForm.device.device_name" :key="index"
                   style="display: flex;align-items: center;justify-content: space-between">
                <span>{{ item }}</span>
                <span style="cursor: pointer">
                  <el-icon size="16" @click.stop="handleDelete(index)">
                          <Coffee/>
                        </el-icon>
                </span>
              </div>
            </td>
            <td colspan="1">仪器型号</td>
            <td colspan="2" style="width: 100px;">
              <div v-for="(item,index) in waterForm.device.device_model" :key="index">{{ item }}</div>
            </td>
            <td colspan="1">仪器编号</td>
            <td colspan="3" style="width: 100px;">
              <div v-for="(item,index) in waterForm.device.device_number" :key="index">{{ item }}</div>
            </td>
            <td colspan="4">内标元素</td>
            <td colspan="5">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.nbys"/>
            </td>
            <td colspan="4">内标响应范围</td>
            <td colspan="5">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.nbxyfw"/>
            </td>
          </tr>
          <tr>
            <td colspan="3">仪器条件</td>
            <td colspan="15">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.yqtj"/>
            </td>
            <td colspan="3" rowspan="2">计算公式</td>
            <td colspan="8" rowspan="2">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.js_formula"/>
            </td>
          </tr>
          <tr>
            <td colspan="3">样品前处理</td>
            <td colspan="15">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.process"/>
            </td>
          </tr>
          <tr style="text-align: center;">
            <td colspan="2">备注</td>
            <td colspan="23">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.notes"/>
            </td>
          </tr>
        </table>
        <!--      <input id="uploadBtn" type="file" @change="loadExcel"/>-->
        <div id="luckysheet" style="width:100%;height:500px;"></div>
      </el-card>
    </div>
    <div v-show="!switchAB">
      <index :water-form="waterForm" :list-b="listB"></index>
    </div>

    <div>
      <Index :water-form="waterForm" :handle-add-water-ph="handleAddWaterPh" :handle-switch="handleSwitch"
             :get-water-capacity="getWaterCapacity" :switch-add="switchAdd" :switch-a-b="switchAB"
             :switch="true"></Index>
    </div>
    <el-dialog title="添加仪器" v-model="assignedDialogVisible" width="30%" center :before-close="handleClose">
      <el-form ref="form" :model="addSampleForm" label-width="90px">
        <el-form-item label="仪器名称：">

          <el-select v-model="addSampleForm.device_name" placeholder="请选择" filterable remote multiple
                     :remote-method="fetchSearchResults">
            <el-option
                v-for="(label, value) in selectedUsers"
                :key="value"
                :label="`${label.device_name} (${label.device_number})`"
                :value="label.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" style="display: flex;justify-content: center">
        <el-button @click="handleClose" style="width: 50%">取 消</el-button>
        <el-button type="primary" style="width: 50%" @click="handleSureSample">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<style scoped>
.card {
  padding: 20px 25px;
}

.table {
  width: 100%;
  border-collapse: collapse;
  /* 表格边框合并 */
  text-align: left;
  /* 默认左对齐 */
  font-size: 14px;
  /* 字体大小 */
  color: #606266;
  /* 默认字体颜色 */
  margin-bottom: 20px;
}

.table th,
.table td {
  border: 1px solid #c2bfbf;
  /* 表格单元格边框颜色 */
  padding: 12px;
  /* 单元格内边距 */
}

.table th {
  background: #f5f7fa;
  /* 表头背景色 */
  font-weight: 600;
  /* 表头字体加粗 */
  color: #303133;
  /* 表头字体颜色 */
  text-align: center;
  /* 表头居中 */
}


.table-td {
  display: flex;
}

::v-deep .el-input__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-select__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-input-group__append {
  background-color: transparent;
  box-shadow: none;
}
</style>
